package com.controller.library;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.action.library.GeneratePaperAction;
import com.action.library.GeneratePaperRandomlyAction;
import com.bean.library.Course;
import com.bean.library.Option;
import com.bean.library.Paper;
import com.bean.library.Subject;

public class GeneratePaperServlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void service(HttpServletRequest request,HttpServletResponse response){
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String testType = (String)request.getSession().getAttribute("test_type");
		Paper paper = null;
		if(testType.equals("exam")){
			int paperId = Integer.parseInt(request.getParameter("paper_id"));
			request.getSession().setAttribute("paperId",paperId);
			GeneratePaperAction generatePaperAction = new GeneratePaperAction();
			try{
				paper = generatePaperAction.generatePaper(paperId);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
		else if(testType.equals("practice")){
			int paperId = Integer.parseInt(request.getParameter("paper_id"));
			request.getSession().setAttribute("paperId",paperId);
			GeneratePaperAction generatePaperAction = new GeneratePaperAction();
			try{
				paper = generatePaperAction.generatePaper(paperId);
			}catch(Exception ex){
				ex.printStackTrace();
			}		
		}
		else if(testType.equals("free")){
			Course selectedCourse = (Course)request.getSession().getAttribute("selectedCourse");
			String courseId = selectedCourse.getCourseId();
			Integer[] problemCountEachDifficulty  = new Integer[6];
			for(int i = 1;i<=5;i++){
				problemCountEachDifficulty[i] = Integer.parseInt(request.getParameter("rank"+i));
			}
			GeneratePaperRandomlyAction generatePaperRandomlyAction = new GeneratePaperRandomlyAction();
			paper = generatePaperRandomlyAction.generatePaperRandomly(courseId, problemCountEachDifficulty);
		}
		else{
			System.out.println("王一然null");			
		}
		
		
		request.getSession().setAttribute("paper", paper);
		Paper partialPaper = new Paper();
		try{
			partialPaper.setPaperName(paper.getPaperName());
			partialPaper.setSubjectList(paper.getSubjectList(0, 10));
		}catch(Exception e){
			e.printStackTrace();
		}
		request.getSession().setAttribute("partialPaper", partialPaper);
		
		try {
			response.sendRedirect("/Exam1/student/page/paper.jsp?" + request.getQueryString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
